package com.zhiqianbao.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhiqianbao.R;
import com.zhiqianbao.adapter.RepayAdapter;
import com.zhiqianbao.entity.Repay;
import com.zhiqianbao.entity.RepayDataInfo;
import com.zhiqianbao.entity.RepayDataInfo.RepayListBean;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorthPurseUtil;
import com.zhiqianbao.view.RepayListView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/27.
 * 测试账号13910212974
 */
public class BeforeRepayFragment extends BaseFragment implements View.OnClickListener{

    TextView repayMoneysTv;
    ImageView repayDialogDetail;
    ImageView repayCouponBt;
    TextView daysFirstTv;
    TextView daysSecondTv;
    TextView daysThirdTv;
    TextView stateTv;
    LinearLayout repayDaysLayout;
    RepayListView norepayLv;
    TextView repayBanksTv;
    ImageView couponImgView;
    TextView couponNameTv;
    TextView couponContentTv;
    Button couponClose;
    TextView couponUsetimeTv;
    RelativeLayout repayCouponLayout;
    Button repayBt;
    TextView repayNotice;
    TextView customerCenter;
    LinearLayout layoutUseRepay;
    LinearLayout layoutNouseRepay;
    SwipeRefreshLayout swipRefresh;
    ScrollView repayScrollview;

    public static final int REQUEST_CODE = 3;
    boolean isDown = false;
    RepayDataInfo loan;
    View view;
    List<RepayListBean> repays;
    String couponId = "";
    String couponType = "";
    RepayListBean repayListBean;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (swipRefresh != null) {
                swipRefresh.setRefreshing(false);
            }
            switch (msg.what) {
                case 1:
                    closeWaitDialog();
                    Object object = msg.obj;
                    //没有还款数据
                    if (null == object) {
                        layoutNouseRepay.setVisibility(View.VISIBLE);
                        layoutUseRepay.setVisibility(View.GONE);
                    } else {
                        try {
                            layoutNouseRepay.setVisibility(View.GONE);
                            layoutUseRepay.setVisibility(View.VISIBLE);
                            loan = (RepayDataInfo) object;
                            repays = loan.getRepayList();
                            //如果没有数据
                            if (repays.isEmpty()) {
                                layoutNouseRepay.setVisibility(View.VISIBLE);
                                layoutUseRepay.setVisibility(View.GONE);
                            } else {
                                if (repays.size() != 0) {
                                    repayListBean = getRepayListBean(repays);
                                    if (repayListBean != null) {
                                        if (loan.getCount() > 0) {
                                            repayCouponBt.setClickable(true);
                                            repayCouponBt.setImageResource(R.drawable.repay_coupn_select);
                                        } else {
                                            repayCouponBt.setClickable(false);
                                            repayCouponBt.setImageResource(R.drawable.repay_coupon_unselect);
                                        }

                                        String days = autoGenericCode(repayListBean.getOverdue());
                                        if (days.length() == 3) {
                                            daysFirstTv.setText(days.substring(0, 1));
                                            daysSecondTv.setText(days.substring(1, 2));
                                            daysThirdTv.setText(days.substring(2, 3));
                                        }
                                        if (repayListBean.getOverdueStatus() == 0) {
                                            daysFirstTv.setTextColor(Color.parseColor("#DA3C21"));
                                            daysSecondTv.setTextColor(Color.parseColor("#DA3C21"));
                                            daysThirdTv.setTextColor(Color.parseColor("#DA3C21"));
                                            stateTv.setText("已逾期");
                                            repayMoneysTv.setText(repayListBean.getRepayTotal() + "");
                                            repayCouponBt.setClickable(false);
                                            repayCouponBt.setImageResource(R.drawable.repay_coupon_unselect);
                                        } else {
                                            daysFirstTv.setTextColor(Color.parseColor("#1573A4"));
                                            daysSecondTv.setTextColor(Color.parseColor("#1573A4"));
                                            daysThirdTv.setTextColor(Color.parseColor("#1573A4"));
                                            //正式
                                            if (0.01 == repayListBean.getRepayTotal()) {
                                                repayMoneysTv.setText("0.01");
                                            } else {
                                                repayMoneysTv.setText(((int) repayListBean.getRepayTotal()) + "");
                                            }
                                            stateTv.setText("离到期");
                                        }
                                        String id = Constants.LOGIN_USER.getId().toString();
                                        List<UserBank> userBanks = UserBank.findWithQuery(UserBank.class,
                                                "select * from user_bank where user_id = ? ", id);
                                        if (userBanks != null && userBanks.size() > 0) {
                                            UserBank userBank = userBanks.get(0);
                                            String bankCard = userBank.getBankCard();
                                            if (bankCard.length() > 4) {
                                                bankCard = bankCard.substring(bankCard.length() - 4);
                                            }
                                            repayBanksTv.setText("        到期日将自动从" + userBank.getDeposit() + "（尾号" +
                                                    bankCard + "）扣款，请保证余额充足！");
                                        } else {
                                            repayBanksTv.setText("");
                                        }
                                        //添加列表数据
                                        RepayAdapter repayAdapter = new RepayAdapter(getActivity(), repays);
                                        norepayLv.setAdapter(repayAdapter);
                                    } else {
                                        layoutNouseRepay.setVisibility(View.VISIBLE);
                                        layoutUseRepay.setVisibility(View.GONE);
                                    }
                                } else {
                                    layoutNouseRepay.setVisibility(View.VISIBLE);
                                    layoutUseRepay.setVisibility(View.GONE);
                                }
                            }
                        } catch (Exception e) {

                        }
                    }
                    break;
                case 0:
//                    showShortToast1("连接超时");
                    closeWaitDialog();
                    break;
            }
            if (isDown) {
                isDown = false;
            } else {
                closeWaitDialog();
            }
        }
    };


    Handler checkRepayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), Constants.HTTP_ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    Result<String> data = (Result<String>) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            //不允许还款
                            if (data.getData().equals("0")) {
                                Toast.makeText(getActivity(), "请等待上一期还款处理完之之后，再进行本期还款。", Toast.LENGTH_SHORT).show();
                                //扣款进行中，请等待扣款结果
                            } else if (data.getData().equals("2")) {
                                Toast.makeText(getActivity(), "本期已经扣款，请等待处理结果。", Toast.LENGTH_SHORT).show();
                            } else {
                                if (repayListBean != null) {
                                    Intent intent = new Intent(getActivity(), RepayVerifyActivity.class);
                                    Repay repay = new Repay();
                                    repay.setId(new Long(repayListBean.getId()));
                                    repay.setLoanId(new Long(repayListBean.getLoanId()));
                                    repay.setOverdue(repayListBean.getOverdue());
                                    repay.setRepayTotal(repayListBean.getRepayTotal());
                                    repay.setTerms(repayListBean.getTerms());
                                    repay.setState(repayListBean.getState());
                                    intent.putExtra("repay", repay);
                                    intent.putExtra("couponId", couponId);
                                    Log.i("优惠券id.12.", couponId);
                                    intent.putExtra("couponType", couponType);
                                    getActivity().startActivity(intent);
                                    //取消掉优惠券布局全部信息
                                    couponId = "";
                                    couponType = "";
                                    couponContentTv.setText("");
                                    repayCouponLayout.setVisibility(View.GONE);
                                }
                            }
                        } else {
                            Toast.makeText(getActivity(), data.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_before_repay1, null);
        initView(view);
        if (swipRefresh != null) {
            swipRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    //查询借款进度接口
                    if (Constants.LOGIN_USER != null) {//!!!!!暂时性修改判断
                        couponId = "";
                        couponType = "";
                        couponContentTv.setText("");
                        repayCouponLayout.setVisibility(View.GONE);
                        displayBeforeRepayList();
                    }
                }
            });
        }

        if (repayScrollview != null) {
            repayScrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    if (swipRefresh != null) {
                        swipRefresh.setEnabled(repayScrollview.getScrollY() == 0);
                    }
                }
            });
        }
        return view;
    }

    public void initView(View view){
        repayMoneysTv=(TextView)view.findViewById(R.id.repay_moneys_tv);
         repayDialogDetail=(ImageView)view.findViewById(R.id.repay_dialog_detail);
         repayCouponBt=(ImageView)view.findViewById(R.id.repay_coupon_bt);
         daysFirstTv=(TextView)view.findViewById(R.id.days_first_tv);
         daysSecondTv=(TextView)view.findViewById(R.id.days_second_tv);
         daysThirdTv=(TextView)view.findViewById(R.id.days_third_tv);
         stateTv=(TextView)view.findViewById(R.id.state_tv);
         repayDaysLayout=(LinearLayout)view.findViewById(R.id.repay_days_layout);
         norepayLv=(RepayListView)view.findViewById(R.id.norepay_lv);
         repayBanksTv=(TextView)view.findViewById(R.id.repay_banks_tv);
         couponImgView=(ImageView)view.findViewById(R.id.coupon_imgView);
         couponNameTv=(TextView)view.findViewById(R.id.coupon_name_tv);
         couponContentTv=(TextView)view.findViewById(R.id.coupon_content_tv);
         couponClose=(Button)view.findViewById(R.id.coupon_close);
         couponUsetimeTv=(TextView)view.findViewById(R.id.coupon_usetime_tv);
         repayCouponLayout=(RelativeLayout)view.findViewById(R.id.repay_coupon_layout);
         repayBt=(Button)view.findViewById(R.id.repay_bt);
         repayNotice=(TextView)view.findViewById(R.id.repay_notice);
         customerCenter=(TextView)view.findViewById(R.id.customer_center);
         layoutUseRepay=(LinearLayout)view.findViewById(R.id.layout_use_repay);
         layoutNouseRepay=(LinearLayout)view.findViewById(R.id.layout_nouse_repay);
         swipRefresh=(SwipeRefreshLayout)view.findViewById(R.id.swipRefresh);
         repayScrollview=(ScrollView)view.findViewById(R.id.repay_scrollview);
        repayDialogDetail.setOnClickListener(this);
        repayCouponBt.setOnClickListener(this);
        couponClose.setOnClickListener(this);
        repayBt.setOnClickListener(this);
        repayNotice.setOnClickListener(this);
        customerCenter.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (Constants.LOGIN_USER != null) {
            showWaitDialog();
            displayBeforeRepayList();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        cacelCoupon();
    }

    @Override
    public void onClick(View v) {
            if(R.id.repay_dialog_detail==v.getId()) {
                    repayDetailDialog();
            }
            else if(R.id.repay_coupon_bt==v.getId()) {
                if (Constants.LOGIN_USER != null) {
                    Intent intent = new Intent(getActivity(), MyCouponActivity.class);
                    intent.putExtra("serviceType", "2");
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    startActivity(new Intent(getActivity(),
                            WorthPurseUtil.getZhiddActivity().getClass()));
                    getActivity().finish();
                }
            }
            else if(R.id.coupon_close==v.getId()) {
                cacelCoupon();
            }
            else if(R.id.repay_bt==v.getId()) {
                if (repayListBean != null) {
//                    下一个版本可以删除，提示优惠券
//                    if(loan.getCount()>0&&couponId.equals("")
//                            &&repayListBean.getState().equals("0")){
//                        expressCouponDialog();
//                    }
//                    else {
//                        checkPreRepay(String.valueOf(repayListBean.getId()));
//                    }
                    checkPreRepay(String.valueOf(repayListBean.getId()));
                }
            }
            else if(R.id.repay_notice==v.getId()) {
                Intent reimbursementIntent = new Intent(getActivity(), DialogContractActivity.class);
                reimbursementIntent.putExtra("url", "/webview/repaymentNotice");
                reimbursementIntent.putExtra("title", "还款须知");
                startActivity(reimbursementIntent);
            }
            else if(R.id.customer_center==v.getId()) {
                if (Constants.LOGIN_USER != null) {
                    startActivity(new Intent(getActivity(), MessageMainActivity.class));
                } else {
                    Intent mine1 = new Intent(getActivity(),
                            WorthPurseUtil.getZhiddActivity().getClass());
                    startActivity(mine1);
                    getActivity().finish();
                }
        }
    }


    private void displayBeforeRepayList() {
        //请求应还款列表
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> param = new HashMap<>();
                param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                //应还款状态
                param.put("state", Constants.BEFORE_REPAYMENT);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/repay/listNew", param, getActivity());
                if (StringUtils.isBlank(result)) {
                    message.what = 0;
                } else {
                    Result<RepayDataInfo> data = Result.fromJson(result, RepayDataInfo.class);
                    if (data != null) {
                        loan = data.getData();
                        message.what = 1;
                        message.obj = loan;
                    }
                }
                handler.sendMessage(message);

            }
        }).start();
    }

    private void checkPreRepay(final String repayId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> params = new HashMap<>();
                params.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                params.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                params.put("repayId", repayId);
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/repay/checkPreRepay", params, getActivity());
                Message message = new Message();
                if (StringUtils.isBlank(result)) {
                    message.what = getActivity().RESULT_CANCELED;
                } else {
                    message.what = getActivity().RESULT_OK;
                    Result<String> data = Result.fromJson(result, String.class);
                    message.obj = data;
                }
                checkRepayHandler.sendMessage(message);
            }
        }).start();
    }

    public void repayDetailDialog() {
        final AlertDialog builder = new AlertDialog.Builder(getActivity(), R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_repay_detail_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        TextView repay_money_quota = (TextView) view.findViewById(R.id.repay_money_quota);
        TextView repay_procedures_quota = (TextView) view.findViewById(R.id.repay_procedures_quota);
        TextView repay_term_quota = (TextView) view.findViewById(R.id.repay_term_quota);
        TextView repay_procedures = (TextView) view.findViewById(R.id.repay_procedures);
        TextView repay_amount_due_quota = (TextView) view.findViewById(R.id.repay_amount_due_quota);
        if (repayListBean != null) {
            repay_money_quota.setText(repayListBean.getAmount() + "元");
            repay_term_quota.setText(repayListBean.getTerm() + "个月");
            repay_procedures_quota.setText("第" + repayListBean.getTerms() + "期");
            if (repayListBean.getOverdueStatus() == 0) {
                repay_amount_due_quota.setText(repayListBean.getRepayTotal() + "元");
            } else {
                if (0.01 == repayListBean.getRepayTotal()) {
                    repay_amount_due_quota.setText("0.01" + "元");
                } else {
                    repay_amount_due_quota.setText(((int) repayListBean.getRepayTotal()) + "元");
                }

            }

            if (repayListBean.getTerm() == 1) {
                repay_procedures.setVisibility(View.GONE);
                repay_procedures_quota.setVisibility(View.GONE);
            } else {
                repay_procedures.setVisibility(View.VISIBLE);
                repay_procedures_quota.setVisibility(View.VISIBLE);
            }
        }
        Button button = (Button) view.findViewById(R.id.positiveButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                String name = data.getStringExtra("name");
                String end_time = data.getStringExtra("end_time");
                String note = data.getStringExtra("note");
                couponId = data.getStringExtra("couponId");
                couponType = data.getStringExtra("couponType");
                repayCouponLayout.setVisibility(View.VISIBLE);
                couponNameTv.setText(name);
                couponUsetimeTv.setText(end_time);
                //暂时截串处理
                if (note.length() > 1) {
                    couponContentTv.setText(note.substring(0, note.length() - 1));
                }
            }
        }
    }

    /**
     * 不够位数的在前面补0，保留code的长度位数字
     *
     * @param code
     * @return
     */
    private String autoGenericCode(int code) {
        String result = "";
        // 保留code的位数
        result = String.format("%0" + 3 + "d", code);
        return result;
    }

    /**
     * 取消界面展示优惠券
     */
    public void cacelCoupon() {
        couponId = "";
        couponType = "";
        repayCouponLayout.setVisibility(View.GONE);
        couponContentTv.setText("");
    }

    /**
     * 有优惠券未选优惠券时，提示有可用优惠券
     */
    public void expressCouponDialog() {
        final AlertDialog builder = new AlertDialog.Builder(getActivity(), R.style.Dialog).create();
        builder.show();
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_express_coupon_layout, null);
        builder.getWindow().setContentView(view);
        builder.setCanceledOnTouchOutside(false);
        TextView title = (TextView) view.findViewById(R.id.title);
        TextView repay_money = (TextView) view.findViewById(R.id.repay_money);
        Button button = (Button) view.findViewById(R.id.positiveButton);
        Button cacelButton = (Button) view.findViewById(R.id.cacelButton);
        title.setText("还款详情");
        repay_money.setText("你本次还款有可使用的优惠券，是否使用？");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constants.LOGIN_USER != null) {
                    Intent intent = new Intent(getActivity(), MyCouponActivity.class);
                    intent.putExtra("serviceType", "2");
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    startActivity(new Intent(getActivity(),
                            WorthPurseUtil.getZhiddActivity().getClass()));
                    getActivity().finish();
                }
                builder.dismiss();
            }
        });

        cacelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
    }

    /**
     * 排除已还款的期数，找出该期应还的期数
     *
     * @param listBeens
     * @return
     */
    public RepayListBean getRepayListBean(List<RepayListBean> listBeens) {
        for (RepayListBean listBean : listBeens) {
            if (listBean.getState().equals("0")) {
                return listBean;
            }
        }
        return null;
    }
}